package com.ytu.clouddisk.vdisk;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.drawable.LevelListDrawable;
import android.widget.ListView;
import android.widget.Toast;

import com.ytu.clouddisk.face.BrowserActivity;
import com.ytu.clouddisk.face.LVAdapter;
import com.ytu.clouddisk.face.ListViewItemData;
import com.ytu.clouddisk.face.R;
import com.ytu.clouddisk.utils.Varibles;

public class VDiskControl {

	/**
	 * 产生URL
	 * 
	 * @param m
	 *            操作对象
	 * @param a
	 *            方法名
	 * @return
	 */
	public static String makeURL(String m, String a) {
		return Varibles.VDISK_BASE_URL + "?m=" + m + "&a=" + a;
	}

	public static String VDiskPost() {
		return null;
	}

	public static void getList(Context mContext, String token) {
		HttpPost httpRequest = new HttpPost(makeURL("dir", "getList"));
		ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair("token", token));
		postParams.add(new BasicNameValuePair("dir_id", "0"));
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(postParams,
					HTTP.UTF_8));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		httpRequest.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		HttpClient httpclient = new DefaultHttpClient();
		String strResult = null;
		try {
			HttpResponse httpResponse = httpclient.execute(httpRequest); // 提交
			int statusCode = httpResponse.getStatusLine().getStatusCode(); // 获得结果码200是正确
			if (statusCode == HttpStatus.SC_OK)
				strResult = EntityUtils.toString(httpResponse.getEntity());

		} catch (ParseException e) {
			Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT);
			return;
		} catch (IOException e) {
			Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT);
			return;
		}
		// Log.e("WeiboKu", "strResult :" + strResult);

		JSONObject sData = null;
		List<String> list = new ArrayList<String>();

		try {
			sData = new JSONObject(strResult);
			JSONObject jss = sData.getJSONObject("data");
			JSONArray jsonArray = jss.getJSONArray("list");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
				FileBean calendarInfo = new FileBean();
				calendarInfo.setId(jsonObject2.getString("id"));
				// calendarInfo.setDir_id(jsonObject2.getString("dir_id"));
				calendarInfo.setName(jsonObject2.getString("name"));
				list.add(calendarInfo.getName());
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		LevelListDrawable levelListDrawable = (LevelListDrawable) mContext
				.getResources().getDrawable(R.drawable.listview_image_file); // 获取图片列表
		ListViewItemData mListViewItemData = new ListViewItemData(
				levelListDrawable, list, list.size());

		ListView mListView = BrowserActivity.getListView();
		LVAdapter mListViewAdapter = new LVAdapter(mContext, mListViewItemData);
		BrowserActivity.getListView().setAdapter(mListViewAdapter);
	}

/*	public static void getList2(Context mContext, String token) {
		HttpPost httpRequest = new HttpPost(makeURL("file", "upload_file"));
		ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair("token", token));
		postParams.add(new BasicNameValuePair("dir_id", "0"));
		postParams.add(new BasicNameValuePair("cover", "no"));
		postParams.add(new BasicNameValuePair("file", ""2进制流 ));
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(postParams,
					HTTP.UTF_8));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		httpRequest.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		HttpClient httpclient = new DefaultHttpClient();
		String strResult = null;
		try {
			HttpResponse httpResponse = httpclient.execute(httpRequest); // 提交
			int statusCode = httpResponse.getStatusLine().getStatusCode(); // 获得结果码200是正确
			if (statusCode == HttpStatus.SC_OK)
				strResult = EntityUtils.toString(httpResponse.getEntity());

		} catch (ParseException e) {
			Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT);
		} catch (IOException e) {
			Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT);
		}

	}

*/

	public static boolean upload(String token,String fileName,String filePath, String type)
			throws ParseException, IOException {
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpPost httppost = new HttpPost(makeURL("file","upload_file"));
		File file = new File(filePath);
		MultipartEntity mpEntity = new MultipartEntity();
		ContentBody cbFile = new FileBody(file,fileName,type,"UTF-8");
		                                              //设置文件名的编码方式 中文乱码
		mpEntity.addPart("file", cbFile);
		mpEntity.addPart("dir_id", new StringBody("0", "UTF-8", null));
		mpEntity.addPart("cover", new StringBody("yes", "UTF-8", null));
		mpEntity.addPart("token", new StringBody(token, "UTF-8", null));

		httppost.setEntity(mpEntity);
		System.out.println("executing request " + httppost.getRequestLine());
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity resEntity = response.getEntity();

		System.out.println(response.getStatusLine());
		if (resEntity != null) {
			String result = EntityUtils.toString(resEntity);
			resEntity.consumeContent();
			return true;
		}
		
		httpclient.getConnectionManager().shutdown();
		return false;
	}

	/**
	 * HAMCSHA256加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptHMAC(String data, String key) throws Exception {
		Mac mac = Mac.getInstance("HmacSHA256");
		mac.init(new SecretKeySpec(key.getBytes(), mac.getAlgorithm()));
		mac.update(data.getBytes());
		String strDes = bytesToHexString(mac.doFinal());
		return strDes;
	}

	/**
	 * 转字节为十六进制
	 * 
	 * @param bytes
	 * @return
	 */
	private static String bytesToHexString(byte[] bytes) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}

}
